<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Product extends ShopBackEndController {
    public function __construct() {
        parent::__construct();
        $this->load->model('repo/shop_product_model', 'shop_product_model');
        $this->load->model('repo/shop_category_model', 'shop_category_model');
    }

    private function intialPaging() {
        $this->mypaging->setLimit(PRODUCT_LIMIT);
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function index($pageIndex = 1) {
        $this->load->library('mypaging');
        $option = array();
        $folder = $this->input->get('f', true);
        if($folder!==false && $folder=='trash'){
            $option = array(
                'a.active_flg'=>OFF
            );
        } else {
            $option = array(
                'a.active_flg'=>ON
            );
        }

        $this->intialPaging();
        $this->mypaging->setCount($this->shop_product_model->countAllProduct($option));
        $this->mypaging->setMainURL(mns_product_paging_url());
        $pagingBar     = $this->mypaging->getBar($pageIndex);
        $offset        = ($pageIndex - 1) * PRODUCT_LIMIT;
        $aProduct      = $this->shop_product_model->paging(PRODUCT_LIMIT, $offset, $option);
        $aShopCategory = $this->shop_category_model->getAll(array(), array('a.id', 'a.title', 'a.slug'), $this->shop->getId());
        $aReturn       = array(
            'pageTitle' => 'Sản phẩm',
            'aProduct' => $aProduct,
            'aShopCategory' => $aShopCategory,
            'pagingBar' => $pagingBar);
        $this->renderView('backend/shop/product/index', $aReturn);
    }

    public function search($pageIndex = 1) {
        $this->load->library('mypaging');
        $searchkey = $this->input->get('s', true);
        $this->intialPaging();
        $this->mypaging->setCount($this->shop_product_model->countSearch($searchkey));
        $this->mypaging->setMainURL(mns_product_search_paging_url());
        $pagingBar = $this->mypaging->getBar($pageIndex, array('s' => $searchkey));
        $offset = ($pageIndex - 1) * PRODUCT_LIMIT;
        $aProduct = $this->shop_product_model->search(PRODUCT_LIMIT, $offset, $searchkey);
        $aReturn = array(
            'pageTitle' => 'Sản phẩm',
            'aProduct' => $aProduct,
            'pagingBar' => $pagingBar,
            'searchkey' => $searchkey);
        $this->renderView('backend/shop/product/index', $aReturn);
    }

    public function get($slug) {
        $this->load->helper('file');
        $product = $this->shop_product_model->get($slug, array('a.id >' => 0));
        if (count($product) == 0) {
            show_404();
        }
        $aProductCate = $this->shop_category_model->getAll(array(), array('a.id', 'a.title', 'a.slug'), $this->shop->getId());
        $aProductInSet = $this->shop_product_model->getProductInSet($product->getId());
        $aReturn = array(
            'pageTitle' => $product->getTitle(),
            'product' => $product,
            'aProductCate' => $aProductCate,
            'aProductInSet' => $aProductInSet,
            'action_link' => "cap-nhat");

        $this->renderView('backend/shop/product/update', $aReturn);
    }

    public function insert() {
        $limit = $this->shop_product_model->checkLimitUploadProduct($this->shop->getId());
        if(count($limit)<1){
            $aReturn = array('pageTitle' => 'Hết số lượng sản phẩm có thể thêm');
            $this->renderView('backend/shop/product/limit', $aReturn);
            return;
        }
        $this->load->helper('file');
        $this->load->model('entity/product_entity', 'Product_Entity');
        $product                    = new Product_Entity();
        $product->shop_slug         = $this->shop->getSlug();
        $product->shop_image_folder = $this->image_folder;
        $aProductCate               = $this->shop_category_model->getAll(array(), array('a.id', 'a.title', 'a.slug'), $this->shop->getId());
        $aProductInSet              = array();
        $aReturn                    = array(
            'pageTitle'     => 'Thêm sản phẩm',
            'product'       => $product,
            'aProductCate'  => $aProductCate,
            'aProductInSet' => $aProductInSet,
            'action_link'   => mns_page_url('san-pham/them-moi'));
        $this->renderView('backend/shop/product/new', $aReturn);
    }

    public function doInsert() {
        $aResult = array();
        $product            = $this->input->post('product', true);
        $aProductDetail     = $this->input->post('product_detail', true);
        $productTemp        = $this->input->post('product');
        $aProductDetailTemp = $this->input->post('product_detail');

        //validate form data
        $this->setValidate($aProductDetail);
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        //check already exist product
        $curShop = $this->shop_product_model->getCurrentShop();
        $option = array(
            'shop_id' => $curShop->getId(),
            'title' => $product['title'],
            'slug' => $product['slug']);
        $iExist = $this->shop_product_model->checkProductExist($option);
        if ($iExist > 0) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul><li>' . $this->lang->line('product_exists') . '</li></ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        //check already exist detail code
        $liCode = "";
        foreach ($aProductDetail as $index => $pdt) {
            $option['code'] = $pdt['code'];
            $iExistCode = $this->shop_product_model->checkProductCodeExist($option);
            if ($iExistCode > 0) {
                $liCode .= '<li>' . sprintf($this->lang->line('product_detail_code_exists'), $pdt['code']) . '</li>';
            }
        }
        if ($liCode != '') {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . $liCode . '</ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        //product area
        $data = array();
        $date = new DateTime();
        $product['shop_cate_id'] = $product['product_cate'];
        unset($product['product_cate']);
        $product['shop_id'] = $curShop->getId();
        $parentCate = $this->shop_category_model->getParentCategory($product['shop_cate_id']);
        $product['cate_id'] = $parentCate->getId();
        if (isset($product['delete_flg']) && $product['delete_flg'] == 1) {
            $product['deleted_at'] = $date->format(DATE_TIME_FORMAT);
        }
        $product['created_at'] = $date->format(DATE_TIME_FORMAT);
        if(isset($product['delete_flg'])){
            unset($product['delete_flg']);
        }
        $data['product'] = $product;

        //product_detail area
        $data['product_detail_new'] = array();
        $this->load->library('MyImage', 'myimage');
        $curShop = $this->shop_product_model->getCurrentShop();
        foreach ($aProductDetail as $index => $pdt) {
            //set image
            if (isset($pdt['image']) && trim($pdt['image'])!='') {
                $imageInfo = explode('/', $pdt['image']);
                if (isset($imageInfo[0])) {
                    if ($imageInfo[1] == '') {
                        show_404();
                    } else {
                        if ($imageInfo[0] == 'temp') {
                            $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, PRODUCT_IMAGE_URL, $imageInfo[1]);
                        }
                        $pdt['image'] = $imageInfo[1];
                    }
                }
            }
            //set avatar
            if(isset($pdt['is_avatar']) && $pdt['is_avatar']==1){
                $pdt['is_avatar']=1;
            } else {
                $pdt['is_avatar']=0;
            }
            $pdt['created_at'] = $date->format(DATE_TIME_FORMAT);
            if (isset($pdt['delete_flg']) && $pdt['delete_flg'] == 0) {
                $pdt['deleted_at'] = $date->format(DATE_TIME_FORMAT);
                unset($pdt['created_at']);
            }
            unset($pdt['delete_flg']);
            array_push($data['product_detail_new'], $pdt);
        }

        //insert
        if (count($aResult) == 0) {
            $result = $this->shop_product_model->insert($data);
            if ($result) {
                $aResult = array('code' => 1, 'text' => $this->lang->line('insert_success'), 'href'=> mns_product_single_url($product['slug']));
            } else {
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('system_error'),
                    'text' => $this->lang->line('insert_fail'));
            }
        }
        $this->renderJSON($aResult);
    }

    private function setValidate($aDetail) {
        $this->form_validation->set_rules('product[title]',        'lang:product_title', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('product[slug]',         'lang:product_slug',  'trim|required|callback_slug_check|xss_clean');
        $this->form_validation->set_rules('product[product_cate]', 'lang:product_cate',  'trim|required|numeric|xss_clean');
        foreach ($aDetail as $index => $d) {
            //set more lang
            $this->lang->language['product_deltail_code_'       .$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_code');
            $this->lang->language['product_deltail_price_old_'  .$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_price_old');
            $this->lang->language['product_deltail_price_new_'  .$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_price_new');
            $this->lang->language['product_deltail_description_'.$index] = "<b>Chi tiết ".$index."</b>: ".$this->lang->line('product_deltail_description');

            $this->form_validation->set_rules("product_detail[$index][code]",       'lang:product_deltail_code_'       .$index, 'trim|required|max_length[50]|xss_clean');
            $this->form_validation->set_rules("product_detail[$index][price_old]",  'lang:product_deltail_price_old_'  .$index, 'trim|callback_blank_numeric_check|xss_clean');
            $this->form_validation->set_rules("product_detail[$index][price_new]",  'lang:product_deltail_price_new_'  .$index, 'trim|callback_blank_numeric_check|xss_clean');
            $this->form_validation->set_rules("product_detail[$index][description]",'lang:product_deltail_description_'.$index, 'trim|max_length[1000]|xss_clean');
        }

        $this->form_validation->set_error_delimiters('<li>', '</li>');
    }

    public function doUpdate() {
        $aResult      = array('code'=>0, 'title'=>$this->lang->line('system_error'));
        $product      = $this->input->post('product', true);
        $product_temp = $this->input->post('product');
        unset($product_temp['update_case']);
        if(isset($product['update_case'])){
            //get id
            $id = isset($product['id']) && $product['id']!='' ? $this->encrypt->decode($product_temp['id']) : false;
            if($id!==false){
                unset($product['id']);
                if($product['update_case'] == UPDATE_FULL || $product['update_case'] == UPDATE_LIST_ITEM){
                    $aResult = $this->fullUpdate($id, $product, $product_temp);
                } else {
                    unset($product['update_case']);
                    $aResult = $this->flashUpdate($id, $product);
                }
            }
        }
        $this->renderJSON($aResult);
    }

    private function fullUpdate($id, $product, $productTemp) {
        $aResult            = array();
        $data               = array();
        $date               = new DateTime();
        $aProductDetail     = $this->input->post('product_detail', true);
        $aProductDetailTemp = $this->input->post('product_detail');

        $this->setValidate($aProductDetail);
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>',
                );
            return $aResult;
        }
        //check already exist product
        $option = array(
            'shop_id' => $this->shop->getId(),
            'title'   => $product['title'],
            'slug'    => $product['slug']
        );
        $iExist = $this->shop_product_model->checkProductExist($option, $id);
        if ($iExist > 0) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul><li>' . $this->lang->line('product_exists') . '</li></ul>',
                );
            return $aResult;
        }
        //check already exist detail code
        $liCode = "";
        foreach ($aProductDetail as $index => $pdt) {
            $option['code'] = $pdt['code'];
            $productDetailId = $this->encrypt->decode($aProductDetailTemp[$index]['id']);
            $iExistCode = $this->shop_product_model->checkProductCodeExist($option, $productDetailId);
            if ($iExistCode > 0) {
                $liCode .= '<li>' . sprintf($this->lang->line('product_detail_code_exists'), $pdt['code']) . '</li>';
            }
        }
        if ($liCode != '') {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . $liCode . '</ul>',
                );
            return $aResult;
        }

        //product area
        $product['shop_cate_id'] = $product['product_cate'];
        //set flag
        if($product['update_case']==UPDATE_FULL){
            if (isset($product['delete_flg']) && $product['delete_flg'] == 1) {
                $product['deleted_at'] = $date->format(DATE_TIME_FORMAT);
            } else {
                $product['deleted_at'] = NULL;
                $product['updated_at'] = $date->format(DATE_TIME_FORMAT);
            }
        }
        if (isset($product['active_flg']) && $product['active_flg'] == 1) {
            $product['active_flg'] = 1;
        } else {
            $product['active_flg'] = 0;
        }
        if (isset($product['sale_flg']) && $product['sale_flg'] == 1) {
            $product['sale_flg'] = 1;
        } else {
            $product['sale_flg'] = 0;
        }
        unset($product['delete_flg']);
        unset($product['id']);
        unset($product['product_cate']);
        $data['product'] = $product;

        //product_detail area
        $data['product_detail_update'] = array();
        $data['product_detail_new'] = array();
        $this->load->library('MyImage', 'myimage');
        $curShop = $this->shop_product_model->getCurrentShop();
        foreach ($aProductDetail as $index => $pdt) {
            //set image
            if (isset($pdt['image'])) {
                $imageInfo = explode('/', $pdt['image']);
                if (count($imageInfo) != 2) {
                    show_404();
                }
                if ($imageInfo[0] == 'temp') {
                    $this->myimage->move_upload('uploads/public/'.$this->image_folder.'/', TEMP_FOLDER_URL, PRODUCT_IMAGE_URL, $imageInfo[1]);
                }
                $pdt['image'] = $imageInfo[1];
            }

            if($product['update_case']==UPDATE_FULL){
                if (isset($pdt['publish_flg']) && $pdt['publish_flg'] == 1) {
                    $pdt['deleted_at'] = NULL;
                    $pdt['updated_at'] = $date->format(DATE_TIME_FORMAT);
                } else {
                    $pdt['deleted_at'] = $date->format(DATE_TIME_FORMAT);
                }

                //set avatar
                if(isset($pdt['is_avatar']) && $pdt['is_avatar']==1){
                    $pdt['is_avatar']=1;
                } else {
                    $pdt['is_avatar']=0;
                }
            }
            unset($pdt['delete_flg']);
            unset($pdt['publish_flg']);

            if (isset($pdt['id'])) {
                $productDetailId = null;
                if (isset($pdt['id'])) {
                    $productDetailId = $this->encrypt->decode($aProductDetailTemp[$index]['id']);
                }
                unset($pdt['id']);
                $data['product_detail_update'][$productDetailId] = $pdt;
            } else {
                $pdt['product_id'] = $productId;
                $pdt['created_at'] = $date->format(DATE_TIME_FORMAT);
                $pdt['updated_at'] = $date->format(DATE_TIME_FORMAT);
                array_push($data['product_detail_new'], $pdt);
            }
        }
        unset($data['product']['update_case']);
        $result = $this->shop_product_model->update($id, $data);
        if ($result) {
            $aResult = array(
                'code'       => 1,
                'text'       => $this->lang->line('update_success'),
                'back_href'  => mns_product_single_url($product['slug']),
                'front_href' => product_url($product['slug'])
                );
        } else {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error'),
                'text' => $this->lang->line('update_fail'));
        }
        return $aResult;
    }

    private function flashUpdate($id, $product) {
        $aResult = array('code'=>0, 'title'=>$this->lang->line('system_error'));
        $date    = get_current_date();
        $data    = array();
        $aResult = array();

        if(isset($product['active_flg'])) {
            if($product['active_flg'] == 0 || $product['active_flg'] == 1) {
                $data['active_flg'] = $product['active_flg'];
                $data['updated_at'] = $date;
            }
        }

        if(isset($product['sale_flg'])) {
            if($product['sale_flg'] == 0 || $product['sale_flg'] == 1) {
                $data['sale_flg'] = $product['sale_flg'];
                $data['updated_at'] = $date;
            }
        }

        if(isset($product['delete_flg'])) {
            if ($product['delete_flg']==1){
                $data['deleted_at'] = $date;
            } elseif ($product['delete_flg']==0){
                $data['deleted_at'] = NULL;
                $data['updated_at'] = $date;
            }
        }

        $result = $this->shop_product_model->flash_update($id, $data);
        if($result){
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success')
                );
        }
        return $aResult;
    }
}
?>